//
//  FindVC.m
//  WOQIEarjoy
//
//  Created by 孙鹏飞 on 2023/11/7.
//  Copyright © 2023 WOQI. All rights reserved.
//

#import "FindVC.h"
#import "FindHeadCell.h"
#import "FindTypeCell.h"
#import "FindCommodityCell.h"
#import "BannerModel.h"

#import "RequestManager.h"

#import <BIRouteModule/BIRouteManager.h>
#import <BIToolModule/BIProjectDefine.h>
#import <BIProjectModule/BIAppDefine.h>

#import <YYNavigation/YYNavigation.h>
#import <Masonry/Masonry.h>
#import <MJRefresh/MJRefresh.h>
#import <MJExtension/MJExtension.h>

static NSString * const FindHeadCellID = @"FindHeadCellID";
static NSString * const FindTypeCellID  = @"FindTypeCellID";
static NSString * const FindCommodityCellID  = @"FindCommodityCellID";
static NSString * const HeadID = @"HeadID";

#define WEAKSELF __weak typeof(self) weakSelf = self;


#define URL_main @"https://earjoy.watchfun.cn/api/app"

//获取轮播列表 http://test-earjoy.watchfun.cn:180/api/app/mall/getBannerList
#define app_getBannerList [NSString stringWithFormat:@"%@/%@",URL_main,@"mall/getBannerList"]

//获取主功能列表 http://test-earjoy.watchfun.cn:180/api/app/mall/getIconList
#define app_getMainFunctionList [NSString stringWithFormat:@"%@/%@",URL_main,@"mall/getIconList"]

//获取商品列表 http://test-earjoy.watchfun.cn:180/api/app/mall/getProductList
#define app_getProductList [NSString stringWithFormat:@"%@/%@",URL_main,@"mall/getProductList"]

@interface FindVC ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic,strong) UIView * bgView;
@property(nonatomic,strong) UICollectionView * myCollectionView;
@property(nonatomic,strong) NSMutableArray * bannerArray;
@property(nonatomic,strong) NSMutableArray * mainFunArray;
@property(nonatomic,strong) NSMutableArray * productListArray;
@property(nonatomic,strong) NSMutableArray * productListModelArray;
@property (nonatomic,assign) BOOL loadOver; //加载完毕
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign)float  wightHight; //宽高比

@end

@implementation FindVC

+ (void)load {
    [[BIRouteManager sharedInstance] registerCMD:@"find" objectOrClass:self];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
//    [[ADShowManager AD_sharedManager] showAD:@"find"];

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor loadColorFromString:@"#20232A"];
//    self.view.lee_theme.LeeConfigBackgroundColor(Color1);

    self.page=1;
    
    [self setUI];
    [self getImageSize];
    [self setData];
    [self requstGoodsList];
    
}
-(void)setUI{
//    UIView * view = [UIView new];
//    view.frame = CGRectMake(0, 0, BIScreenWidth, k_TabBarHeight);
//    view.backgroundColor = KRedColor;
//    [self.view addSubview:view];
//
//    self.yy_navigationBar.isHiddenNaviBar = YES;
    self.yy_navigationItem.title = BILocalizedString(@"商城");
    
    UIImageView * bgImgV = [[UIImageView alloc]init];
    bgImgV.frame = CGRectMake(0, 0, BIScreenWidth, BIScreenHeight);
//    bgImgV.image = [UIImage imageNamed:@"pic／渐变"];
    bgImgV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgImgV];
    
//    UILabel* leftLab = [[UILabel alloc]init];
//    leftLab.frame = CGRectMake(0,BINavigationBarHeight-44,BIScreenWidth, 44);
//    leftLab.textAlignment = NSTextAlignmentCenter;
//    leftLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
////    leftLab.lee_theme.LeeConfigTextColor(Color2);
//    leftLab.textColor = [UIColor loadColorFromString:@"#000000"];
////    leftLab.text =  NTVLocalized(@"商城", nil);
//    leftLab.text = BILocalizedString(@"商城");
//    [self.view addSubview:leftLab];
    
    [self.view addSubview:self.myCollectionView];
    [self.myCollectionView mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(BINavigationBarHeight + 5);
//        make.top.equalTo(self.view.mas_top).offset(BITabBarHeight);
        make.left.right.bottom.equalTo(self.view).offset(0);
    }];
    @weakify(self);
    self.myCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{//下拉刷新
        @strongify(self);
        if (self.loadOver) {
            [self.myCollectionView.mj_header endRefreshing];
            return;
        }
        self.page=1;
        [self setData];
        [self requstGoodsList];
    }];
    MJRefreshAutoNormalFooter *footerRefresh = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        if (self.loadOver) {
            [self.myCollectionView.mj_footer endRefreshing];
            return;
        }
        self.page++;
        [self requstGoodsList];
    }];
//    [footerRefresh setTitle:NTVLocalized(@"商品已加载完", nil) forState:MJRefreshStateNoMoreData];
    [footerRefresh setTitle:BILocalizedString(@"商品已加载完") forState:MJRefreshStateNoMoreData];
    self.myCollectionView.mj_footer = footerRefresh;
}
-(void)requstGoodsList{
    @weakify(self);
    NSDictionary * dic = @{@"pageNum":[NSString stringWithFormat:@"%ld",(long)self.page],@"pageSize":@"20"};
//    [RequestManager GET:app_getProductList parameters:dic isHud:nil isWindow:NO success:^(id responseObject) {
//        
//        if([responseObject[@"data"][@"totalPage"] intValue] == self.page){
//            weakSelf.myCollectionView.mj_header.state = MJRefreshStateNoMoreData;
//            weakSelf.myCollectionView.mj_footer.state = MJRefreshStateNoMoreData;
//            weakSelf.loadOver = YES;
//        }else{
//            weakSelf.myCollectionView.mj_footer.state = MJRefreshStateIdle;
//        }
//        if (self.page == 1) {
//            [self.productListArray removeAllObjects];
//            [weakSelf.myCollectionView.mj_header endRefreshing];
//        }
//        [self.productListArray addObjectsFromArray:responseObject[@"data"][@"list"]];
//        self.productListModelArray = [BannerModel mj_objectArrayWithKeyValuesArray:self.productListArray];
//        [self.myCollectionView reloadData];
//    } failure:^(NSError *error) {
//    }];
    
    [RequestManager GET:app_getProductList parameters:dic isHud:nil isWindow:NO responseCache:^(id responseCache) {
        @strongify(self);
        if (responseCache!=nil) {
            if ([RequestManager isNetwork] == NO) {
                NSArray *arr = responseCache[@"data"][@"list"];
                self.productListModelArray = [BannerModel mj_objectArrayWithKeyValuesArray:arr];
                [self.myCollectionView reloadData];
            }
        }
    } success:^(id responseObject) {
        @strongify(self);
        if([responseObject[@"data"][@"totalPage"] intValue] == self.page){
            self.myCollectionView.mj_header.state = MJRefreshStateNoMoreData;
            self.myCollectionView.mj_footer.state = MJRefreshStateNoMoreData;
            self.loadOver = YES;
        }else{
            self.myCollectionView.mj_footer.state = MJRefreshStateIdle;
        }
        if (self.page == 1) {
            [self.productListArray removeAllObjects];
            [self.myCollectionView.mj_header endRefreshing];
        }
        [self.productListArray addObjectsFromArray:responseObject[@"data"][@"list"]];
        self.productListModelArray = [BannerModel mj_objectArrayWithKeyValuesArray:self.productListArray];
        [self.myCollectionView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)setData{
    [RequestManager GET:app_getBannerList parameters:nil isHud:nil isWindow:NO responseCache:^(id responseCache) {
        if (responseCache!=nil) {
            self.bannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseCache[@"data"]];//字典数组转模型
            [self.myCollectionView reloadData];
        }
    } success:^(id responseObject) {
        self.bannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];//字典数组转模型
        [self.myCollectionView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
    [RequestManager GET:app_getMainFunctionList parameters:nil isHud:nil isWindow:NO responseCache:^(id responseCache) {
        if (responseCache!=nil) {
            self.mainFunArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseCache[@"data"]];//字典数组转模型
            [self.myCollectionView reloadData];
        }
    } success:^(id responseObject) {
        self.mainFunArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];//字典数组转模型
        [self.myCollectionView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)getImageSize{
    WEAKSELF
    [RequestManager GET:app_getBannerList parameters:nil isHud:nil isWindow:NO responseCache:^(id responseCache) {
        if (responseCache!=nil) {
            self.bannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseCache[@"data"]];//字典数组转模型
            if (self.bannerArray.count>0) {
                BannerModel* m = self.bannerArray[0];
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//异步加载
                dispatch_async(queue, ^{
                    //code here
                    NSURL *url = [NSURL URLWithString: m.image ];
                    NSData * data = [NSData dataWithContentsOfURL:url];
                    UIImage * image = [UIImage imageWithData:data];
    //                    NSLog(@"----v1-----%f",image.size.width);
    //                    NSLog(@"----v2-----%f",image.size.height);
                    weakSelf.wightHight = image.size.width/image.size.height;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.myCollectionView reloadData];
                    });
                });
            }
        }
    } success:^(id responseObject) {
        self.bannerArray = [BannerModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];//字典数组转模型
//        DLog(@"---bannerArraybannerArray-------%lu",(unsigned long)self.bannerArray.count);
        if (self.bannerArray.count>0) {
//            DLog(@"2323133131");
            BannerModel* m = self.bannerArray[0];
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//异步加载
            dispatch_async(queue, ^{
                //code here
                NSURL *url = [NSURL URLWithString: m.image ];
                NSData * data = [NSData dataWithContentsOfURL:url];
                UIImage * image = [UIImage imageWithData:data];
//                    NSLog(@"----v1-----%f",image.size.width);
//                    NSLog(@"----v2-----%f",image.size.height);
                weakSelf.wightHight = image.size.width/image.size.height;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.myCollectionView reloadData];
                });
            });
        }
    } failure:^(NSError *error) {
        
    }];

}

#pragma mark - collectionView 代理
//设置collectionView每个区一共有多少个单元格
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else  if(section ==1){
        return self.mainFunArray.count;
    }else{
        return self.productListModelArray.count;
    }
}
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
//    if(section == 1){
//        return UIEdgeInsetsMake(0, 0 ,0, 0);
//    }else{
//        return UIEdgeInsetsMake(0, 0, 0, 0);
//
//    }
//}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if(section == 2){
        return CGSizeMake(BIScreenWidth, 50);
    }
    return CGSizeZero;
}
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    WOXIHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([WOXIHeaderView class]) forIndexPath:indexPath];
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {

        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeadID forIndexPath:indexPath];
        for (UIView *view in header.subviews) { //防止复用
            [view removeFromSuperview];
        }
        header.backgroundColor = [UIColor clearColor];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 30)];
//        label.lee_theme.LeeConfigTextColor(Color2);
        label.textColor = [UIColor loadColorFromString:@"#000000"];
//        label.text = NTVLocalized(@"火热商品抢购", nil);
        label.text = BILocalizedString(@"火热商品抢购");
        label.textAlignment = NSTextAlignmentLeft;
        label.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
        [header addSubview:label];

        return header;
    }else {
        return nil;
    }
}


//设置cell大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (self.wightHight>0) {
            return CGSizeMake(BIScreenWidth,(BIScreenWidth -40)/self.wightHight);
        }else{
            return CGSizeMake(BIScreenWidth,200);
        }
    }else  if(indexPath.section ==1){
        return CGSizeMake((BIScreenWidth - 40 - 60)/4, 120);
    }else{
        return CGSizeMake((BIScreenWidth-52)/2,(BIScreenWidth-52)/2+100);
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        FindHeadCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:FindHeadCellID forIndexPath:indexPath];
        cell.modelArray =  self.bannerArray;
        if (self.wightHight>0) {
            cell.imageHight = (BIScreenWidth -40)/self.wightHight;
        }
//        cell.backgroundColor = KRedColor;
        return cell;
    }else  if(indexPath.section ==1){
        FindTypeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:FindTypeCellID forIndexPath:indexPath];
//        cell.backgroundColor = KGreenColor;
        cell.model = [self.mainFunArray objectAtIndex:indexPath.item];
        return cell;
    }else{
        FindCommodityCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:FindCommodityCellID forIndexPath:indexPath];
        cell.model = [self.productListModelArray objectAtIndex:indexPath.item];

//        cell.backgroundColor = KGrayColor;
        return cell;
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}

#pragma mark - Lazy
- (UICollectionView *)myCollectionView {
    if (!_myCollectionView) {
        //UICollectionView的自动布局
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;//设置滑动方向 ..s
//        layout.minimumInteritemSpacing = 20;  //跟滚动方向垂直的间距
        layout.minimumLineSpacing = 12;       //跟滚动方向相同的间距
        _myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _myCollectionView.backgroundColor = [UIColor clearColor];
        _myCollectionView.delegate = self;
        _myCollectionView.dataSource = self;
//        _myCollectionView.bounces = NO;
//        _myCollectionView.showsVerticalScrollIndicator = NO; //显示垂直滚动指示器
//        _myCollectionView.showsHorizontalScrollIndicator = NO;
//        _myCollectionView. pagingEnabled = YES;
//        _myCollectionView.scrollEnabled = NO;
//        if (@available(iOS 11.0, *)) {  消除默认内边距。不加则从导航栏下开始
//            _myCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        } else {
////            self.automaticallyAdjustsScrollViewInsets = NO;
//        }
        [_myCollectionView registerClass:[FindHeadCell class] forCellWithReuseIdentifier:FindHeadCellID];
        [_myCollectionView registerClass:[FindTypeCell class] forCellWithReuseIdentifier:FindTypeCellID];
        [_myCollectionView registerClass:[FindCommodityCell class] forCellWithReuseIdentifier:FindCommodityCellID];
        [_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeadID];
    }
    return _myCollectionView;
}
- (NSMutableArray *)bannerArray{
    if(!_bannerArray){
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}
- (NSMutableArray *)mainFunArray{
    if(!_mainFunArray){
        _mainFunArray = [NSMutableArray array];
    }
    return _mainFunArray;
}
- (NSMutableArray *)productListArray{
    if(!_productListArray){
        _productListArray = [NSMutableArray array];
    }
    return _productListArray;
}
- (NSMutableArray *)productListModelArray{
    if(!_productListModelArray){
        _productListModelArray = [NSMutableArray array];
    }
    return _productListModelArray;
}

#pragma mark - Replace Method

- (void)languageChanged:(NSNotification *)notification {
    self.yy_navigationItem.title = BILocalizedString(@"商城");
        
    MJRefreshConfig.defaultConfig.languageCode = notification.object;

    MJRefreshAutoNormalFooter *footerRefresh = (MJRefreshAutoNormalFooter *)self.myCollectionView.mj_footer;
    [footerRefresh setTitle:BILocalizedString(@"商品已加载完") forState:MJRefreshStateNoMoreData];

    [self.myCollectionView reloadData];
}

@end
